import 'dart:convert';
import 'package:http/http.dart' as http;

class DeepSeekService {
  static const String _baseUrl = 'https://api.deepseek.com';
  final String _apiKey;

  DeepSeekService(this._apiKey);

  Future<String> getMedicalAdvice(String userQuery) async {
    try {
      final response = await http.post(
        Uri.parse('$_baseUrl/v1/chat/completions'),
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
          'Authorization': 'Bearer $_apiKey',
          'Accept': 'application/json; charset=utf-8',
        },
        body: utf8.encode(jsonEncode({
          'model': 'deepseek-chat',
          'messages': [
            {
              'role': 'system',
              'content':
                  '你是一位专业的医疗顾问，请根据用户的问题提供专业的医疗建议。请使用中文回答，确保输出的是UTF-8编码的中文文本。'
            },
            {'role': 'user', 'content': userQuery}
          ],
          'temperature': 0.7,
          'max_tokens': 2000,
          'stream': false,
        })),
      );

      if (response.statusCode == 200) {
        final data = jsonDecode(utf8.decode(response.bodyBytes));
        final content = data['choices'][0]['message']['content'];
        return content;
      } else {
        final errorBody = utf8.decode(response.bodyBytes);
        throw Exception(
            'Failed to get response from DeepSeek API: ${response.statusCode}\nError: $errorBody');
      }
    } catch (e) {
      throw Exception('Error communicating with DeepSeek API: $e');
    }
  }
}
